package com.fx.controller;

import com.fx.entity.AdminTempUser;
import com.fx.entity.SysUser;
import com.fx.service.SysRoleService;
import com.fx.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;


public class UserRealm extends AuthorizingRealm {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysRoleService sysRoleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        String roleId = ((AdminTempUser) SecurityUtils.getSubject().getPrincipal()).getFlRoleId();
        String[] perms = sysRoleService.getPerms(roleId);
        String roleCode = sysRoleService.getById(roleId).getFlCode();
        Set<String> sets = new HashSet<>();
        for (String s : perms) {
            String[] str = s.split(",");
            for (String st : str) {
                sets.add(st);
            }
        }
        Set<String> role = new HashSet<String>();
        role.add(roleCode);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(sets);
        info.setRoles(role);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = String.valueOf(token.getPrincipal());
        String password = new String((char[]) token.getCredentials());
        // 查询用户信息
        AdminTempUser user = sysUserService.getByLoginName(username);
        // 账号不存在
        if (user == null || user.getFlName() == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        // 密码错误
        if (!password.equals(user.getFlPwd())) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }
        // 账号锁定
        if (user.getFlStatus() == 1) {
            throw new LockedAccountException("账号已过期,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }

}
